import { useState } from "react";
import { LoginUserApi } from "../../request/userInfo/LoginUser";
import { useAppDispatch } from "../../redux";
import { setIsLogin } from "../../redux/privates/userInfoSlice.ts";
import { useNavigate } from "react-router";



const LoginForm:React.FC=()=>{
    const navigete = useNavigate()
    // 修改仓库内登录状态
    const dispatch = useAppDispatch()
    const [LoginStatus,setLoginStatus] = useState(true)
    const [From,setForm] = useState({
        "username":'',
        "password":''
    })
    // 表单提交函数
    const handleSubmit= async (e:any)=>{
        e.preventDefault()
        const username:String = From.username
        const password:String = From.password
        if (username.length<3 || username.length>13){
            alert("账号长度必须在5~13位之间")
            return
        }
        if (password.length < 10 || password.length>18){
            alert("密码长度必须在10~18位之间")
            return
        }
        const dataJson = JSON.stringify(From)
        const res:any = await LoginUserApi(dataJson)
            if(res === 401){
                setLoginStatus(false)
            }else {

                // 存入token
                localStorage.setItem("userToken",res)
                dispatch(setIsLogin(true))
                navigete("/")
            }  
    }

    // 表单数据改变则触发函数
    const handleInputChange=(e:any)=>{
        const {name,value} = e.target;
        const newFrom = {...From}
        if(name === "username"){
            newFrom.username = value
        }else{
            newFrom.password = value
        }
        setForm(newFrom)
    }


    return (
        <main>
            <form onSubmit={handleSubmit} className="text-center">
                <div>
                    <input type="text"
                    value={From.username}
                    name="username"
                    onChange={handleInputChange}
                    className="bg-neutral-200 my-3.5 w-60 h-9 pl-2 outline-sky-400 rounded-md"
                    placeholder="账号"
                    />
                </div>
                <div>
                    <input type="password"
                    value={From.password}
                    name="password"
                    onChange={handleInputChange}
                    className="bg-neutral-200 my-3.5 w-60 h-9 pl-2 outline-sky-400 rounded-md"
                    placeholder="密码"
                    />
                </div>
                <span className={`${LoginStatus?'hidden':'text-xs text-red-600'}`}>账号或密码错误!</span>
                <div>
                    <input type="submit" 
                    className="bg-sky-400 w-28 h-9 mt-3"
                    onClick={handleSubmit}
                    />
                </div>
            </form>
        </main>
    );
}
export default LoginForm